import link_providers
import movie_providers
import product
import season
import crawled_links

def add_new_link(db,bot,link,product_id,ptype,remote_id,season_id,movie_provider_id,link_provider_id,episode):
	## sanity checks
	if not link_providers.is_valid(db,link_provider_id):
		print "Error: Not a valid link Provider: " + link_provider
		## TODO: create logging here
		return None
	if not movie_providers.is_valid(db,movie_provider_id):
		print "Error: Not a valid movie Provider: %s" % movie_provider_id
		## TODO: create logging here
		return None
	if not product.is_valid(db,product_id,ptype,remote_id):
		print "Error: Not an existing product %s !" % product_id
		## TODO: create logging here
		return None
	if not season.is_valid(db,season_id,product_id,ptype):
		print "Error: Not a valid season %s for %s creating new one" % (season,product)
		## TODO: create logging here
		return None
	cur=db.cursor()
	cur.execute("""select * from crawled_links where link=%s""",link)
	rows=cur.fetchall()
	cur.close()
	samelink=len(rows)
	if samelink==0:
		return crawled_links.insert_new(db,link,product_id,season_id,movie_provider_id,link_provider_id,episode)
	elif samelink>0:
		print "Warnning: Duplicate link : " + link
		## TODO: create logging here
		return None

def get_product_id(db,product_name,ptype,remote_id):
	pid=product.get_id(db,product_name,ptype,remote_id)
	if pid==-1:
		pid=product.insert_new(db,product_name,ptype,remote_id)
	return pid

def get_season_id(db,product_id,ptype,remote_id,season_name):
	sid=season.get_id(db,season_name,ptype)
	if sid==-1 and product.is_valid(db,product_id,ptype,remote_id):
		sid=season.insert_new(db,product_id,ptype,season_name)
	return sid

def get_link_provider(db,provider_name):
	return link_providers.get_id(db,provider_name)

def get_movie_provider(db,provider_name):
	return movie_providers.get_id(db,provider_name)
